package main.leetcode.clockin.September;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 47. 全排列 II
 *
 * <p>给定一个可包含重复数字的序列，返回所有不重复的全排列。
 *
 * <p>示例: 输入: [1,1,2] 输出: [ [1,1,2], [1,2,1], [2,1,1] ]
 */
public class day18 {
    private List<List<Integer>> res;

    public static void main(String[] args) {
        System.out.println(new day18().permuteUnique(new int[] {1, 1, 2}));
    }

    public List<List<Integer>> permuteUnique(int[] nums) {
        res = new ArrayList<>();
        Arrays.sort(nums);
        boolean[] isVisited = new boolean[nums.length];
        dfs(nums, new ArrayList<>(), isVisited);
        return res;
    }

    private void dfs(int[] nums, List<Integer> cur, boolean[] isVisited) {
        if (cur.size() == nums.length) {
            res.add(new ArrayList<>(cur));
            return;
        }

        for (int i = 0; i < nums.length; ++i) {
            if (isVisited[i]) {
                continue;
            }
            if (i > 0 && nums[i] == nums[i - 1] && !isVisited[i - 1]) {
                continue;
            }
            cur.add(nums[i]);
            isVisited[i] = true;
            dfs(nums, cur, isVisited);
            isVisited[i] = false;
            cur.remove(cur.size() - 1);
        }
    }
}
